//
//  DDCalendarDetailViewController.m
//  ialone
//
//  Created by 陆翀 on 16/1/13.
//  Copyright © 2016年 JasperSong. All rights reserved.
//

#import "DDCalendarDetailViewController.h"
#import "DDSoundDetalisTableViewCell.h"
#import "PKRequestManager.h"
#import "DDSoundDetalisTableViewCell2.h"
#import "DDSoundDetalisTableViewCell3.h"
#import "FMDB.h"
#import "UMSocial.h"
#import "DDLoginViewController.h"
#import "DDManager.h"

@interface DDCalendarDetailViewController ()<UIWebViewDelegate,UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,UMSocialUIDelegate>
@property (nonatomic,strong) UIWebView *webview;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) NSMutableArray *dataArray2;

@property (nonatomic, strong) FMDatabase *db;

@end

@implementation DDCalendarDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _webview = [[UIWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    // 通过一个NSURLRequest来加载一个UIWebView
    //[_webView loadRequest:request];
    
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_html5]];
    //把网站内容的二进制转化为一个字符串
    
    NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    
    NSRange range = [str rangeOfString:@"//goAPP"];
    NSRange range2 = [str rangeOfString:@"goApp();"];
    NSRange range3 = NSMakeRange(range.location, range2.length + range2.location - range.location);
    NSString *str1 = [str stringByReplacingCharactersInRange:range3 withString:@""];
    
    NSRange range4 = [str rangeOfString:@"</section> -->"];
    NSRange range5 = [str rangeOfString:@" <!-- article-end -->"];
    NSRange range6 = NSMakeRange(range4.location, range5.length + range5.location - range4.location);
    
    
    
    
    
    NSString *str2 = [str1 stringByReplacingCharactersInRange:range6 withString:@""];

    
    //str = [str stringByReplacingOccurrencesOfString:@"" withString:@" "];
    
    [_webview loadHTMLString:str2 baseURL:nil];
    _webview.scrollView.delegate = self;
    // _webView.delegate = self;
    [self.view addSubview:_webview];                                                                                                                                                                                                                                                           
    
    [self addTableView];
    [self addUpData];
    
    //[self.view addSubview:_webView];
    
    
    [self.leftButton addTarget:self action:@selector(leftButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.leftButton setImage:[UIImage imageNamed:@"item_cancel@2x"] forState:(UIControlStateNormal)];
    
    // 分享
    [self.share setImage:[UIImage imageNamed:@"iconfont-fenxiang"] forState:(UIControlStateNormal)];
    [self.share addTarget:self action:@selector(share:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
//    // 收藏
//    [self.collection setImage:[UIImage imageNamed:@"wujiaoxingkong"] forState:(UIControlStateNormal)];
//    [self.collection setImage:[UIImage imageNamed:@"wujiaoxingman"] forState:(UIControlStateSelected)];
//    [self.collection addTarget:self action:@selector(collection:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    
    self.topView.alpha = 0.05;
    self.stateView.alpha = 0.05;
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.stateView.alpha = 0.1 + (scrollView.contentOffset.y)/250 ;
    self.topView.alpha =0.1 + (scrollView.contentOffset.y)/250;
}
- (void)leftButton:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addUpData
{
    
    NSString *string = @"http://static.owspace.com/index.php?m=Home&c=Api&from=webapp&a=getArticleData&post_id=";
    NSString *string2 = [NSString stringWithFormat:@"%@%@",string,_pageid];
    [PKRequestManager requestWithUrl:string2 parmDic:nil method:GET succeedWithData:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        self.dataArray = [NSMutableArray array];
        self.dataArray2 = [NSMutableArray array];
        for (NSDictionary *oneDic in dic[@"datas"][@"comment"][@"hots"]) {
            DDSoundDetalisModel *model = [[DDSoundDetalisModel alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            //[model setValue:dic[@"datas"][@"digg"] forKey:@"digg"];
            [self.dataArray addObject:model];
        }
        
        DDSoundDetalisModel *model = [[DDSoundDetalisModel alloc] init];
        [model setValue:dic[@"datas"][@"digg"] forKey:@"digg"];
        [self.dataArray2 addObject:model];
        
        [self.tableView reloadData];
        
    } failedWithError:^(NSError *connectionError) {
        
    }];
}



- (void)addTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    self.tableView.backgroundColor = [UIColor blackColor];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    
    // 把WebView设置表头
    self.tableView.tableHeaderView = _webview;
    
    DDSoundDetalisTableViewCell3 *foot= [[DDSoundDetalisTableViewCell3 alloc]initWithFrame:CGRectMake(0, kScreenHeight - 60, kScreenWidth, 60)];
    foot.backgroundColor = [UIColor whiteColor];
    [foot.button addTarget:self action:@selector(footerButton:) forControlEvents:(UIControlEventTouchUpInside)];
    self.tableView.tableFooterView = foot;
    
    [self.tableView registerClass:[DDSoundDetalisTableViewCell class] forCellReuseIdentifier:@"SoundDetalisTableViewCell"];
    
    [self.tableView registerClass:[DDSoundDetalisTableViewCell2 class] forCellReuseIdentifier:@"DDSoundDetalisTableViewCell2"];
    
    
    
}

// 表尾点击方法
- (void)footerButton:(UIButton *)sender
{
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.dataArray.count + 1 >= 4) {
        return 4;
        
    }
    
    return self.dataArray.count + 1;
    
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    if (indexPath.row == 0) {
        
        DDSoundDetalisTableViewCell2 *cell2 = [tableView dequeueReusableCellWithIdentifier:@"DDSoundDetalisTableViewCell2"];
        DDSoundDetalisModel *model = self.dataArray2[indexPath.row];
        cell2.model = model;
        return cell2;
    }
    else{
        DDSoundDetalisTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SoundDetalisTableViewCell"];
        DDSoundDetalisModel *model = self.dataArray[indexPath.row - 1];
        cell.model = model;
        return cell;
    }
    
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 267;
        
    }
    else
    {
        DDSoundDetalisModel *model = self.dataArray[indexPath.row - 1];
        CGFloat lableHeight = [DDSoundDetalisTableViewCell cellHeightForModel:model];
        return 20 + 10 + lableHeight + 20 + 30 + 20;
        
    }
    
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

// 设置webView自适应高度
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    CGFloat height = [[_webview stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] floatValue];
    _webview.frame = CGRectMake(0, 0, kScreenWidth, height);
    UIScrollView *tempView=(UIScrollView *)[_webview.subviews objectAtIndex:0];
    
    tempView.scrollEnabled=NO;
    tempView.contentSize = CGSizeMake(kScreenWidth, height);
    self.tableView.tableHeaderView = _webview;
    
}


//// 收藏
//- (void)collection:(UIButton *)sender
//{
//    //    sender.selected = !sender.selected;
//    //
//    if (sender.selected == YES)
//    {
//        
//    }
//    else
//    {
//        if ([[DDManager sharedHandle] islogin] == NO) {
//            DDLoginViewController *login = [[DDLoginViewController alloc]init];
//            [self.navigationController pushViewController:login animated:YES];
//        }else
//        {
//            sender.selected = !sender.selected;
//            //FMDB插入的时候必须是个对象如果表里面一个字段是int类型,插入的时候需要插入一个NSNumber对象
//            [_db executeUpdate:@"INSERT INTO CollectList (username,html5,pageid,category,author,title,thumbnail) values(?,?,?,?,?,?,?)",[[DDManager sharedHandle] username],_html5,_pageid,_category,_author,_titlename,_thumbnail];
//        }
//        
//    }
//    
//}



// 分享
- (void)share:(UIButton *)sender
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5698e86ae0f55afff7002b97"
                                      shareText:@"<单读> 单读 懂你"
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToQQ,nil]
                                       delegate:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
